package com.fgw.service.impl;

import com.fgw.common.ServerResponse;
import com.fgw.component.JedisClient;
import com.fgw.dao.OnlinedataMapper;
import com.fgw.pojo.Onlinedata;
import com.fgw.service.IOnlineDataService;
import com.fgw.util.JsonUtils;
import com.fgw.vo.OnlineDataListVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by lyj on 2017/9/14.
 */
@Service("iOnlineDataService")
public class OnlineDataServiceImpl implements IOnlineDataService{

    @Resource
    private OnlinedataMapper onlinedataMapper;

    @Autowired
    private JedisClient jedisClient;

    //redis缓存定义的key
    @Value("REDIS_ONLINEDATA_KEY")
    private  String REDIS_ONLINEDATA_KEY;

    /**
     * 在线资料title列表
     * @return
     */
    @Override
    public ServerResponse<List<Onlinedata>> getTitleOnlineData() {

        //添加缓存
        //查询数据库之前先查询缓存，如果有直接返回

        //从redis中取缓存数据
        try {
            String json=jedisClient.hget(REDIS_ONLINEDATA_KEY,"");
            if(!StringUtils.isBlank(json)){
                //把json转换成List
                List<Onlinedata> list= JsonUtils.jsonToList(json,Onlinedata.class);
                return ServerResponse.createBySuccess(list);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        List<Onlinedata> onlinedataList =onlinedataMapper.getTitleOnlinData();

       /* List<Onlinedata> list=new ArrayList<>();

        for (Onlinedata temp:onlinedataList){
            Onlinedata tempList=new Onlinedata();
            tempList.setOtitle(temp.getOtitle());
            list.add(tempList);
        }

        OnlineDataListVo onlineDataListVoList =new OnlineDataListVo();
        onlineDataListVoList.setOnlinedataList(list);*/

        //返回结果之前，向缓存中添加数据

        try {
            //为了规范key可以使用hash
            //定义一个保存内容的key，
            //value是list，需要把list转换成json数据。
           // jedisClient.hset(REDIS_CONTENT_KEY, cid+"", JsonUtils.objectToJson(list));
            jedisClient.hset(REDIS_ONLINEDATA_KEY,"",JsonUtils.objectToJson(onlinedataList));
        }catch (Exception e){
            e.printStackTrace();
        }


        return  ServerResponse.createBySuccess(onlinedataList);

    }
}
